package com.orange.learnspringbootmail.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;

@Slf4j
@Service
public class MailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    @Autowired
    private TemplateEngine templateEngine;


    public void sendMail() {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            //发送人，不可少
            messageHelper.setFrom(mailSender.getUsername());
            //设置邮件目标地址
            messageHelper.setTo("cyan-lemon@qq.com");
            //设置主题
            messageHelper.setSubject("电影开播通知");
            messageHelper.setSentDate(new Date());

            Context context = new Context();
            //模板上的动态数据
            HashMap<String, Object> map = new HashMap<>();
            map.put("username", "cyan-lemon");
            map.put("movie", "超神学院：诸神降临");
            context.setVariables(map);
            //设置邮件模板
            String content = this.templateEngine.process("mail.html", context);
            //设置右键内容，true表示开启HTML
            messageHelper.setText(content, true);
            //发送右键
            this.mailSender.send(mimeMessage);
            log.info("发送邮件成功....");
        } catch (MessagingException e) {
            log.info("发送邮件失败....");
            e.printStackTrace();
        }
    }
}
